//
//  PerfectInformationViewController.m
//  孕妙
//
//  Created by 是源科技 on 16/4/15.
//  Copyright © 2016年 是源科技. All rights reserved.
//

#import "PerfectInformationViewController.h"
#import "AFHTTPRequestOperationManager.h"
#import "AFNetworking.h"
#import "AFURLResponseSerialization.h"
#import "AFHTTPSessionManager.h"
#import "PersonCenterViewController.h"


@interface PerfectInformationViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIPickerViewDelegate, UIPickerViewDataSource>
@property (nonatomic,strong)UITextField *nameTextField;
@property (nonatomic,strong)UILabel *heightLabel;
@property (nonatomic,strong)UILabel *ageLabel;
@property (nonatomic,strong)UILabel *workStrongLabel;
@property (nonatomic,strong)UILabel *yunqianLabel;
@property (nonatomic,strong)UILabel *currentLabel;
@property (nonatomic,strong)UILabel *lastYuejingLabel;

@property (nonatomic,weak)UIButton *touxaingButton;

@property (nonatomic,strong)UIView *allView;

@property (nonatomic,strong)SettingAlertController *riqiAlert;
@property (nonatomic,strong)SettingAlertController *dataAlert;

@property (nonatomic,strong)UIView *helpView;
@property (nonatomic,strong)UIImage *m_selectImage;
@property (nonatomic,weak)UIImagePickerController *pickImage;
@property (nonatomic,copy)NSString *filePath;
@property (nonatomic,copy)NSString *selectTime;

@property (nonatomic,copy)NSString *userName;
//选择器
@property (nonatomic,strong)xianshikuang *pickerWindow;

@property (nonatomic,weak)UIView *xuanzeqiView;

@property (nonatomic,strong)NSArray *weightIntArray; //体重整数部分
@property (nonatomic,strong)NSArray *weightFloattArray; //体重小数部分
@property (nonatomic,strong)NSArray *heightIntArray; //身高整数部分
@property (nonatomic,strong)NSArray *workLevelArray; //劳动强度

@end

@implementation PerfectInformationViewController
{
    NSString *selectIntStr;    //获取整数值
    NSString *selectFloatStr;  //获取小数值
    NSString *valueStr;     //设置string格式
}

//体重的整数部分
-(NSArray *)weightIntArray
{
    if(!_weightIntArray)
    {
        NSMutableArray *tempAaary = [NSMutableArray array];
        for (NSInteger index = 30; index <= 150; index++) {
            NSString *str = [NSString stringWithFormat:@"%ld", (long)index];
            [tempAaary addObject:str];
        }
        _weightIntArray = [NSArray arrayWithArray:tempAaary];
    }
    return _weightIntArray;
}
//体重的小数部分
-(NSArray *)weightFloattArray
{
    if(!_weightFloattArray)
    {
        _weightFloattArray = @[@"0", @"1", @"2", @"3", @"4",@"5", @"6", @"7",@"8", @"9"];

    }
    return _weightFloattArray;
}
//身高的整数部分
-(NSArray *)heightIntArray
{
    if(!_heightIntArray)
    {
        NSMutableArray *tempAaary = [NSMutableArray array];
        for (NSInteger index = 30; index <= 250; index++) {
            NSString *str = [NSString stringWithFormat:@"%ld", (long)index];
            [tempAaary addObject:str];
        }
        _heightIntArray = [NSArray arrayWithArray:tempAaary];
    }
    return _heightIntArray;
}

-(NSArray *)workLevelArray
{
    if(!_workLevelArray)
    {
        _workLevelArray = @[@"轻度劳动",@"中度劳动",@"重度劳动"];
    }
    return _workLevelArray;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"完善信息";
    self.m_selectImage = nil;
   
    //设置右按钮
    UIButton *saveButton = [UIButton buttonWithType:UIButtonTypeCustom];
    saveButton.frame =  CGRectMake(0, 0, 50.0f, 30.0f);
    [saveButton setTitle:@"保存" forState:normal];
    [saveButton setTitleColor:YMColor(255, 218, 245) forState:UIControlStateNormal];
    UIBarButtonItem *saveButtonItem = [[UIBarButtonItem alloc] initWithCustomView:saveButton];
    self.navigationItem.rightBarButtonItem = saveButtonItem;
    [saveButton addTarget:self action:@selector(saveInforMation) forControlEvents:UIControlEventTouchUpInside];
    [self viewAndTouxiangLayout];
    //选择器设置
    self.dataAlert = [[SettingAlertController alloc] init];
    self.dataAlert.alertTitle = @"数据设置";
    [self.view addSubview:self.dataAlert.view];
    [self addChildViewController:self.dataAlert];
    self.dataAlert.view.alpha = 0;
    
    self.riqiAlert = [[SettingAlertController alloc] init];
    self.riqiAlert.alertTitle = @"提醒时间设置";
    self.riqiAlert.contentType = ALertContentTypePickerView;
    self.riqiAlert.pickerView.datePickerMode = UIDatePickerModeDate;
    [self.view addSubview:self.riqiAlert.view];
    [self addChildViewController:self.riqiAlert];
    self.riqiAlert.view.alpha = 0;
    
    UIView *view1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kDeviceWidth, kDeviceHeight)];
    view1.backgroundColor = [UIColor blackColor];
    self.xuanzeqiView = view1;
    self.xuanzeqiView.hidden = YES;
    self.xuanzeqiView.alpha = 0.5;
    [self.view addSubview:view1];
    
    self.helpView = [[UIView alloc]initWithFrame:CGRectMake(kDeviceWidth / 16.0, kDeviceHeight / 5.7, kDeviceWidth / 8.0 * 7, kDeviceHeight / 1.5)];
    self.helpView.layer.cornerRadius = 12.0;
    self.helpView.layer.borderWidth = 0.5;
    self.helpView.layer.borderColor = [YMColor(252, 160, 207)CGColor];
    self.helpView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.helpView];
    [self addNeirongTohelpView:self.helpView];
    
    self.helpView.hidden = YES;
    
    if([[[NSUserDefaults standardUserDefaults]objectForKey:@"isUserName"] isEqualToString:@"haveUserName"])
    {
        [self getUserInformation];
    }
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    if([passValue passValue].accountHaveFlag == YES)
    {
        UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        backButton.frame =  CGRectMake(0, 0, 30.0f, 30.0f);
        [backButton setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
        UIBarButtonItem *backButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
        self.navigationItem.leftBarButtonItem = backButtonItem;
        backButton.userInteractionEnabled = NO;
    }
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
//    [_pickerWindow removeFromSuperview];
    self.pickerWindow = nil;
    self.navigationItem.hidesBackButton = NO;
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.nameTextField resignFirstResponder];
}

//获取用户信息
-(void)getUserInformation
{
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    
    NSString *urlString = @"http://120.24.178.16:8080/Health/baby/getDevAccountInfo.do";
    NSURL *url = [[NSURL alloc]initWithString:urlString];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:2];
    request.HTTPMethod = @"POST";
    NSString *str = [NSString stringWithFormat:@"account=%@&userName=*",[[NSUserDefaults standardUserDefaults]objectForKey:@"userAccount"]];
    
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    
    //        NSOperationQueue *queue = [NSOperationQueue mainQueue];
    NSOperationQueue *queue = [[NSOperationQueue alloc]init];
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        if (data)
        {
            // 请求成功
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
//            YMLog(@"dict = %@",dict);
            NSArray *arr = [dict objectForKey:@"data"];
            NSDictionary *dicccc = [arr lastObject];
            NSDictionary *date = [dicccc objectForKey:@"menstrualdate"];
            NSString *cure = [date objectForKey:@"time"];
            NSDate *tempDate = [NSDate dateWithTimeIntervalSince1970:[cure longLongValue] / 1000];
            NSCalendar *cal = [NSCalendar currentCalendar];
            NSUInteger unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekOfMonth | NSCalendarUnitWeekday;
            NSDateComponents *commm = [cal components:unit fromDate:tempDate];
            NSString *yearString = [NSString stringWithFormat:@"%ld",(long)commm.year];
            NSString *monthString = [NSString stringWithFormat:@"%ld",(long)commm.month];
            NSString *dayString = [NSString stringWithFormat:@"%ld",(long)commm.day];
            
            dispatch_async(dispatch_get_main_queue(), ^{
            self.nameTextField.text = [dicccc objectForKey:@"userName"];
            self.userName = [dicccc objectForKey:@"userName"];
            self.heightLabel.text = [NSString stringWithFormat:@"%@ cm",[dicccc objectForKey:@"height"]];
            self.ageLabel.text = [NSString stringWithFormat:@"%@",[dicccc objectForKey:@"age"]];
            self.yunqianLabel.text = [NSString stringWithFormat:@"%@ kg",[dicccc objectForKey:@"preWeight"]];
            self.currentLabel.text = [NSString stringWithFormat:@"%@ kg",[dicccc objectForKey:@"weight"]];
            self.lastYuejingLabel.text = [NSString stringWithFormat:@"%@-%02d-%02d",yearString,[monthString intValue],[dayString intValue]];
            if([[dicccc objectForKey:@"workRank"]intValue] == 1)
            {
                self.workStrongLabel.text = @"轻度劳动";
            }
            if([[dicccc objectForKey:@"workRank"]intValue] == 2)
            {
                self.workStrongLabel.text = @"中度劳动";
            }
            if([[dicccc objectForKey:@"workRank"]intValue] == 3)
            {
                self.workStrongLabel.text = @"重度劳动";
            }
            [self.touxaingButton setImage:self.touxiangImage forState:UIControlStateNormal];
            self.m_selectImage = self.touxiangImage;
            });
        }
    }];
        
    });
}


-(void)viewAndTouxiangLayout
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 64, kDeviceWidth, kDeviceHeight / 3.8)];
    [self.view addSubview:view];
    CGFloat viewH = view.frame.size.height;
    UIButton *touxiangButton = [[UIButton alloc]initWithFrame:CGRectMake((kDeviceWidth / 2.0 - viewH / 3.0 * 2 / 3.0 * 2 / 2.0), viewH / 3.0 * 2 / 6.0, viewH / 3.0 * 2 / 3.0 * 2, viewH / 3.0 * 2 / 3.0 * 2)];
    [touxiangButton setBackgroundImage:[UIImage imageNamed:@"personal_Portrait"] forState:UIControlStateNormal];
    touxiangButton.layer.cornerRadius = touxiangButton.frame.size.width / 2.0;
    touxiangButton.layer.masksToBounds = YES;
    self.touxaingButton = touxiangButton ;
    self.touxaingButton.contentMode = UIViewContentModeScaleAspectFit;
    [view addSubview:touxiangButton];
    
    [touxiangButton addTarget:self action:@selector(selectTouxiang) forControlEvents:UIControlEventTouchUpInside];
    
    
    UILabel *touxiangLabel = [[UILabel alloc]initWithFrame:CGRectMake(kDeviceWidth / 3.0, viewH / 3.0 * 2 / 6.0 * 5, kDeviceWidth / 3.0, 30)];
    touxiangLabel.text = @"点击选择头像";
    touxiangLabel.textAlignment = NSTextAlignmentCenter;
    touxiangLabel.textColor = YMColor(175, 175, 175);
    [view addSubview:touxiangLabel];
    
//    UIButton *locationButton = [[UIButton alloc]initWithFrame:CGRectMake(kDeviceWidth - 80, viewH / 5.0, 30, 30)];
//    [locationButton setImage:[UIImage imageNamed:@"personal_location"] forState:UIControlStateNormal];
//    [view addSubview:locationButton];
//    
//    UILabel *locationLabel = [[UILabel alloc]initWithFrame:CGRectMake(kDeviceWidth - 95, viewH / 5.0 + 30, 60, 30)];
//    locationLabel.text = @"您的位置";
//    locationLabel.textAlignment = NSTextAlignmentCenter;
//    locationLabel.textColor = YMColor(190, 190, 190);
//    locationLabel.font = [UIFont boldSystemFontOfSize:14.0];
//    [view addSubview:locationLabel];
    
//    UILabel *stateLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, viewH / 3.0 * 2, kDeviceWidth / 3.0, viewH / 3.0)];
//    stateLabel.text = @"您目前的状态";
//    stateLabel.font = [UIFont systemFontOfSize:14.0];
//    stateLabel.textColor = YMColor(175, 175, 175);
//    [view addSubview:stateLabel];
//    
//    UIView *yunqiView = [[UIView alloc]initWithFrame:CGRectMake(kDeviceWidth / 3.0 + 10, viewH / 3.0 * 2, (kDeviceWidth -kDeviceWidth / 3.0 - 20), viewH / 3.0)];
//    [view addSubview:yunqiView];
//    
//    for(int i = 0;i < 3;i++)
//    {
//        CGFloat w = yunqiView.frame.size.width;
//        CGFloat h = yunqiView.frame.size.height;
//        UIView *littleView = [[UIView alloc]initWithFrame:CGRectMake(w / 3.0 * i, 0, w / 3.0, h)];
//        littleView.tag = i;
//        [yunqiView addSubview:littleView];
//        if(littleView.tag == 0)
//        {
//            [self addButtonAndLabelToView:littleView andButtonImageName:@"personal_Selected" andLabelString:@"备孕期"];
//        }
//        if(littleView.tag == 1)
//        {
//            [self addButtonAndLabelToView:littleView andButtonImageName:@"personal_Unselected" andLabelString:@"怀孕期"];
//        }
//        if(littleView.tag == 2)
//        {
//            [self addButtonAndLabelToView:littleView andButtonImageName:@"personal_Selected" andLabelString:@"育儿期"];
//        }
//    }
    
    
    self.heightLabel = [[UILabel alloc]init];
    self.ageLabel = [[UILabel alloc]init];
    self.workStrongLabel = [[UILabel alloc]init];
    self.yunqianLabel = [[UILabel alloc]init];
    self.currentLabel = [[UILabel alloc]init];
    self.lastYuejingLabel = [[UILabel alloc]init];
    
    self.allView = [[UIView alloc]initWithFrame:CGRectMake(0, 64 + viewH - viewH / 4.0, kDeviceWidth, kDeviceHeight - 64 - viewH + viewH / 4.0)];
    [self.view addSubview:self.allView];
    CGFloat buttonH = (kDeviceHeight - 76 - viewH + viewH / 4.0) / 7;
    CGFloat viewY = 0;
    for(int i = 0;i <= 7;i++)
    {
        UIView *buttonView = [[UIView alloc]initWithFrame:CGRectMake(0, viewY, kDeviceWidth, buttonH)];
        buttonView.backgroundColor = [UIColor whiteColor];
        buttonView.tag = i;
        [self.allView addSubview:buttonView];
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, viewY + buttonH, kDeviceWidth, 1)];
        label.backgroundColor = YMColor(221, 221, 221);
        [self.allView addSubview:label];
        viewY += buttonH + 1;
        if(i == 2)
        {
            viewY += 5;
        }
       if(buttonView.tag == 0)
       {
           [self allKindOfButtonLayoutToView:buttonView andTitleName:@"姓        名" andmiaoshuString:nil andLabel:nil];
           self.nameTextField = [[UITextField alloc]init];
           self.nameTextField.frame = CGRectMake(buttonView.frame.size.width / 4.0, 0, buttonView.frame.size.width / 4.0 * 3, buttonView.frame.size.height);
           self.nameTextField.placeholder = @"请输入真实姓名";
           self.nameTextField.textColor = YMColor(205, 205, 205);
           [buttonView addSubview:self.nameTextField];
       }
        if(buttonView.tag == 1)
        {
            [self allKindOfButtonLayoutToView:buttonView andTitleName:@"身        高" andmiaoshuString:@"选择身高" andLabel:self.heightLabel];
        }
        if(buttonView.tag == 2)
        {
           [self allKindOfButtonLayoutToView:buttonView andTitleName:@"生        日" andmiaoshuString:@"选择生日" andLabel:self.ageLabel];
        }
        if(buttonView.tag == 3)
        {
            [self allKindOfButtonLayoutToView:buttonView andTitleName:@"工作强度" andmiaoshuString:@"轻度劳动" andLabel:self.workStrongLabel];
            UIButton *workStrongBtn = [[UIButton alloc]initWithFrame:CGRectMake(kDeviceWidth / 2.0, buttonView.frame.size.height / 4.0, buttonView.frame.size.height / 2.0, buttonView.frame.size.height / 2.0)];
            [workStrongBtn setImage:[UIImage imageNamed:@"personal_help"] forState:UIControlStateNormal];
            [buttonView addSubview:workStrongBtn];
            [workStrongBtn addTarget:self action:@selector(openHelpView) forControlEvents:UIControlEventTouchUpInside];
        }
        if(buttonView.tag == 4)
        {
            [self allKindOfButtonLayoutToView:buttonView andTitleName:@"孕前体重" andmiaoshuString:@"选择体重" andLabel:self.yunqianLabel];
        }
        if(buttonView.tag == 5)
        {
            [self allKindOfButtonLayoutToView:buttonView andTitleName:@"当前体重" andmiaoshuString:@"当前体重" andLabel:self.currentLabel];
        }
        if(buttonView.tag == 6)
        {
            [self allKindOfButtonLayoutToView:buttonView andTitleName:@"末次月经" andmiaoshuString:@"选择日期" andLabel:self.lastYuejingLabel];
        }
    }
}
//怀孕时期选择
-(void)addButtonAndLabelToView:(UIView *)view andButtonImageName:(NSString *)btnName andLabelString:(NSString *)labelStr
{
    CGFloat w = view.frame.size.width;
    CGFloat h = view.frame.size.height;
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(0, h / 3.0, h / 3.0, h / 3.0)];
    [btn setImage:[UIImage imageNamed:btnName] forState:UIControlStateNormal];
    btn.tag = view.tag;
    [view addSubview:btn];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(h / 3.0 + 3, 0, w - h / 3.0, h)];
    label.text = labelStr;
    label.textColor = YMColor(170, 170, 170);
    label.font = [UIFont systemFontOfSize:14.0];
    [view addSubview:label];
    [btn addTarget:self action:@selector(selectHuaiYunDurtion:) forControlEvents:UIControlEventTouchUpInside];
}

//添加各项信息
-(void)allKindOfButtonLayoutToView:(UIView *)view andTitleName:(NSString *)titleName andmiaoshuString:(NSString *)miaoshuStr andLabel:(UILabel *)neirongLabel
{
    CGFloat w = view.frame.size.width;
    CGFloat h = view.frame.size.height;
    UILabel *label = [[UILabel alloc]init];
    label.frame = CGRectMake(0, 0, w / 4.0, h);
    label.text = titleName;
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = YMColor(189, 72, 136);
    [view addSubview:label];
    
    neirongLabel.frame = CGRectMake(w / 4.0, 0, w / 4.0 * 3, h);
    neirongLabel.text = miaoshuStr;
    neirongLabel.textColor = YMColor(205, 205, 205);
    [view addSubview:neirongLabel];
    
    if(view.tag != 0)
    {
        UIImageView *jiantouImageView = [[UIImageView alloc]initWithFrame:CGRectMake(w - 30 - h / 3.0, h / 3.0, h / 3.0, h / 3.0)];
        jiantouImageView.image = [UIImage imageNamed:@"personal_》small"];
        [view addSubview:jiantouImageView];
        
        UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(w / 4.0, 0, w / 4.0 * 3, h)];
        btn.tag = view.tag;
        [view addSubview:btn];
        
        [btn addTarget:self action:@selector(prefectPersonInformation:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    
}

//点击了选择器的确定按钮
- (void)clickSureButton:(UIButton *)btn
{
    valueStr = nil;
//    _pickerWindow.dianL.hidden = YES;
    _pickerWindow.hidden = YES;
    _pickerWindow.selectPickerView.delegate = nil;
    _pickerWindow.selectPickerView.dataSource = nil;
    self.xuanzeqiView.hidden = YES;
    [self.pickerWindow removeFromSuperview];

    //身高
    if(btn.tag == 1)
    {
        valueStr = [NSString stringWithFormat:@"%@ cm", selectIntStr];
        self.heightLabel.text = valueStr;
    }
    //工作强度
    if(btn.tag == 3)
    {
        valueStr = [NSString stringWithFormat:@"%@", selectIntStr];
        self.workStrongLabel.text = valueStr;
    }
    //孕前体重
    if(btn.tag == 4)
    {
        valueStr = [NSString stringWithFormat:@"%@.%@ kg", selectIntStr, selectFloatStr];
        self.yunqianLabel.text = valueStr;
        [_pickerWindow.dianL removeFromSuperview];
        
    }
    //当前体重
    if(btn.tag == 5)
    {
        [_pickerWindow.dianL removeFromSuperview];
        valueStr = [NSString stringWithFormat:@"%@.%@ kg", selectIntStr, selectFloatStr];
        self.currentLabel.text = valueStr;
    }
}
//点击了选择器的取消按钮
-(void)clickCancelButton
{
    self.xuanzeqiView.hidden = YES;
    self.pickerWindow.hidden = YES;
    _pickerWindow.selectPickerView.delegate = nil;
    _pickerWindow.selectPickerView.dataSource = nil;
    [_pickerWindow.dianL removeFromSuperview];
    [self.pickerWindow removeFromSuperview];
}
//完善个人信息
-(void)prefectPersonInformation:(UIButton *)btn
{
    [self.nameTextField resignFirstResponder];
    //设置身高
    if(btn.tag == 1)
    {
        _pickerWindow = [[xianshikuang alloc] init];
        [self.view addSubview:_pickerWindow];
        self.xuanzeqiView.hidden = NO;
        [_pickerWindow setInterFace:@"身高"];
        [_pickerWindow addSubview:_pickerWindow.dianL];
        _pickerWindow.dianL.hidden = YES;
        _pickerWindow.selectPickerView.delegate = self;
        _pickerWindow.selectPickerView.dataSource = self;
        _pickerWindow.selectPickerView.tag = btn.tag;
        [_pickerWindow.sureBtn addTarget:self action:@selector(clickSureButton:) forControlEvents:UIControlEventTouchUpInside];
        [_pickerWindow.cancelBtn addTarget:self action:@selector(clickCancelButton) forControlEvents:UIControlEventTouchUpInside];
        _pickerWindow.sureBtn.tag = btn.tag;
        [_pickerWindow.selectPickerView selectRow:125  inComponent:0 animated:YES];
        selectIntStr = self.heightIntArray[125];
    }
    //年龄
    if(btn.tag == 2)
    {
        self.riqiAlert.view.alpha = 1.0;
        self.riqiAlert.alertTitle = @"设置年龄";
        typeof (self) weakSelf = self;
        self.riqiAlert.contentType = ALertContentTypePickerView;
        self.riqiAlert.pickerView.datePickerMode = UIDatePickerModeDate;
            self.riqiAlert.completionSelected = ^(NSArray * results,BOOL confirm){
                if (confirm) {
                    NSDate *time = (NSDate *)results.firstObject;
                    weakSelf.ageLabel.text = [weakSelf toFormatTime:time];
                }
            };
    }
    //工作强度
    if(btn.tag == 3)
    {
        _pickerWindow = [[xianshikuang alloc] init];
        [self.view addSubview:_pickerWindow];
        self.xuanzeqiView.hidden = NO;
       
        [_pickerWindow setInterFace:@"工作强度"];
   
        _pickerWindow.selectPickerView.delegate = self;
        _pickerWindow.selectPickerView.dataSource = self;
        
        _pickerWindow.selectPickerView.tag = 3;
        
        [_pickerWindow.sureBtn addTarget:self action:@selector(clickSureButton:) forControlEvents:UIControlEventTouchUpInside];
        [_pickerWindow.cancelBtn addTarget:self action:@selector(clickCancelButton) forControlEvents:UIControlEventTouchUpInside];
        
        _pickerWindow.sureBtn.tag = btn.tag;
        [_pickerWindow.selectPickerView selectRow:0  inComponent:0 animated:YES];
        selectIntStr = self.workLevelArray[0];
    }
    //孕前体重
    if(btn.tag == 4)
    {
        _pickerWindow = [[xianshikuang alloc] init];
        [self.view addSubview:_pickerWindow];
        self.xuanzeqiView.hidden = NO;
        [_pickerWindow setInterFace:@"孕前体重"];
        [_pickerWindow addSubview:_pickerWindow.dianL];
        _pickerWindow.selectPickerView.delegate = self;
        _pickerWindow.selectPickerView.dataSource = self;
        _pickerWindow.selectPickerView.tag = btn.tag;
        [_pickerWindow.sureBtn addTarget:self action:@selector(clickSureButton:) forControlEvents:UIControlEventTouchUpInside];
         [_pickerWindow.cancelBtn addTarget:self action:@selector(clickCancelButton) forControlEvents:UIControlEventTouchUpInside];
        _pickerWindow.sureBtn.tag = btn.tag;
        [_pickerWindow.selectPickerView selectRow:27 inComponent:0 animated:YES];
        [_pickerWindow.selectPickerView selectRow:3  inComponent:1 animated:YES];
        selectIntStr = self.weightIntArray[27];
        selectFloatStr = self.weightFloattArray[3];

    }
    //当前体重
    if(btn.tag == 5)
    {
        _pickerWindow = [[xianshikuang alloc] init];
        [self.view addSubview:_pickerWindow];
        self.xuanzeqiView.hidden = NO;
        [_pickerWindow setInterFace:@"当前体重"];
        [_pickerWindow addSubview:_pickerWindow.dianL];
        _pickerWindow.selectPickerView.delegate = self;
        _pickerWindow.selectPickerView.dataSource = self;
        _pickerWindow.selectPickerView.tag = btn.tag;
        [_pickerWindow.sureBtn addTarget:self action:@selector(clickSureButton:) forControlEvents:UIControlEventTouchUpInside];
         [_pickerWindow.cancelBtn addTarget:self action:@selector(clickCancelButton) forControlEvents:UIControlEventTouchUpInside];
        _pickerWindow.sureBtn.tag = btn.tag;
        [_pickerWindow.selectPickerView selectRow:27  inComponent:0 animated:YES];
        [_pickerWindow.selectPickerView selectRow:3  inComponent:1 animated:YES];
        selectIntStr = self.weightIntArray[27];
        selectFloatStr = self.weightFloattArray[3];
    }
    if(btn.tag == 6)
    {
        self.riqiAlert.view.alpha = 1.0;
        self.riqiAlert.alertTitle = @"设置月经日期";
        typeof (self) weakSelf = self;
        self.riqiAlert.contentType = ALertContentTypePickerView;
        self.riqiAlert.pickerView.datePickerMode = UIDatePickerModeDate;
        self.riqiAlert.completionSelected = ^(NSArray * results,BOOL confirm){
            if (confirm) {
                NSDate *time = (NSDate *)results.firstObject;
                weakSelf.lastYuejingLabel.text = [weakSelf toFormatTime:time];
                
            }
        };
    }
     _pickerWindow.sureBtn.tag = btn.tag;
    
}
//选择怀孕时期  怀孕 育儿
-(void)selectHuaiYunDurtion:(UIButton *)btn
{
    
}
-(void)saveInforMation
{
//    [self.navigationController popViewControllerAnimated:YES];
    if(![self.nameTextField.text isEqualToString:@""])
    {
        if(![self.heightLabel.text isEqualToString:@"选择身高"])
        {
            if(![self.ageLabel.text isEqualToString:@"选择生日"])
            {
                if(![self.yunqianLabel.text isEqualToString:@"选择体重"])
                {
                    if(![self.currentLabel.text isEqualToString:@"当前体重"])
                    {
                        if(![self.lastYuejingLabel.text isEqualToString:@"选择日期"])
                        {
                            NSString *currentTime = [self getSystemTime];
                            NSRange currentRang = {0,8};
                            currentTime = [currentTime substringWithRange:currentRang];
                            NSString *selectTime = self.lastYuejingLabel.text;
                            NSRange yearRang = {0,4};
                            NSRange monthRang = {5,2};
                            NSRange dayRang = {8,2};
                            NSString *seltctStr = [selectTime substringWithRange:yearRang];
                            seltctStr = [seltctStr stringByAppendingString:[selectTime substringWithRange:monthRang]];
                            seltctStr = [seltctStr stringByAppendingString:[selectTime substringWithRange:dayRang]];
                            self.selectTime = [seltctStr stringByAppendingString:@"000000"];
                            
//                            int days = [self jisuantisnhu:currentTime and:seltctStr];
                            
//                            if(![currentTime isEqualToString:seltctStr] && days <= 280)
//                            {
//                                if(self.m_selectImage != nil)
//                                {
                                    [self postBasicInformationToServices];
//                                    //[MBProgressHUD showMessage:@"正在拼命上传中，请稍后..."];
//                                }
//                                else
//                                {
//                                    [MBProgressHUD showError:@"请选择头像"];
//                                }

//                            }
//                            else
//                            {
//                                [MBProgressHUD showError:@"末次月经日期选择错误"];
//                            }
                        }
                        else
                        {
                            [MBProgressHUD showError:@"请选择末次月经"];
                        }
                    }
                    else
                    {
                        [MBProgressHUD showError:@"请选择当前体重"];
                    }
                }
                else
                {
                    [MBProgressHUD showError:@"请选择孕前体重"];
                }
            }
            else
            {
                [MBProgressHUD showError:@"请选择年龄"];
            }
        }
        else
        {
           [MBProgressHUD showError:@"请选择身高"];
        }
    }
    else
    {
        [MBProgressHUD showError:@"请输入用户名"];
    }
}
//上传用户基本信息到服务器
-(void)postBasicInformationToServices
{
    NSString *workRank = nil;
    if([self.workStrongLabel.text isEqualToString:@"轻度劳动"])
    {
        workRank = @"1";
    }
    if([self.workStrongLabel.text isEqualToString:@"中度劳动"])
    {
        workRank = @"2";
    }
    if([self.workStrongLabel.text isEqualToString:@"重度劳动"])
    {
        workRank = @"3";
    }
    [MBProgressHUD showMessage:@"正在拼命上传中，请稍后..."];
    NSString *urlString = @"http://120.24.178.16:8080/Health/baby/setUserInfo.do";
    NSURL *url = [[NSURL alloc]initWithString:urlString];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:2];
    request.HTTPMethod = @"POST";
    NSString *str = [NSString stringWithFormat:@"account=%@&username=%@&sex=1&age=%@&height=%@&rank=5&preWeight=%@&weight=%@&city=guanghou&menstrualdate=%@&workRank=%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"userAccount"],self.nameTextField.text,self.ageLabel.text,[NSString stringWithFormat:@"%.2f",[self.heightLabel.text floatValue]],[NSString stringWithFormat:@"%.2f",[self.yunqianLabel.text floatValue]],[NSString stringWithFormat:@"%.2f",[self.currentLabel.text floatValue]],self.selectTime,workRank];
//    YMLog(@"str = %@",str);
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    NSOperationQueue *queue = [NSOperationQueue mainQueue];
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        if (data)
        {
            [MBProgressHUD hideHUD];
            // 请求成功
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
//            YMLog(@"dict = %@",dict);
            if([[dict objectForKey:@"code"] isEqualToString:@"0"])
            {
                NSMutableDictionary *params  = [NSMutableDictionary dictionary];
                [params setValue:self.nameTextField.text forKey:@"username"];
                [params setValue:[[NSUserDefaults standardUserDefaults]objectForKey:@"userAccount"] forKey:@"account"];
                [self postFileWithPath:@"http://120.24.178.16:8080/Health/baby/setPhoto.do" param:params image:self.m_selectImage];
            }
            else
            {
                [MBProgressHUD showError:[dict objectForKey:@"message"]];
            }
//            if([[dict objectForKey:@"code"] isEqualToString:@"1"])
//            {
//                [MBProgressHUD showError:@"参数设置不正确"];
//            }
//            if([[dict objectForKey:@"code"] isEqualToString:@"2"])
//            {
//                [MBProgressHUD showError:@"账户不存在"];
//            }
        }
    }];

}
//获取系统时间
-(NSString *)getSystemTime
{
    NSDate *senddate=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYYMMddHHmmss"];
    NSString *locationString=[dateformatter stringFromDate:senddate];
    return locationString;
}

//选择照片
-(void)selectTouxiang
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
    {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate =self;
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        imagePicker.allowsEditing =YES;
        self.pickImage = imagePicker;
        [self presentViewController:self.pickImage animated:YES completion:nil];
//        self.m_selectImage = nil;
    }
    else
    {
        [MBProgressHUD showError:@"访问图片库出错"];
    }
}
//再调用以下委托：
#pragma mark UIImagePickerControllerDelegate
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{ //初始化imageNew为从相机中获得的--
    UIImage *imageNew = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    //设置image的尺寸
    CGSize imagesize = imageNew.size;
    imagesize.height = 100;
    imagesize.width = 100;
    //对图片大小进行压缩--
    imageNew = [self imageWithImage:imageNew scaledToSize:imagesize];
    NSData *imageData = UIImageJPEGRepresentation(imageNew,0.5); // 0.00001
//    if(self.m_selectImage == nil)
    {
        self.m_selectImage = [UIImage imageWithData:imageData];
        [self.touxaingButton setImage:self.m_selectImage forState:UIControlStateNormal];
        [self saveImage:self.m_selectImage WithName:@"shiyuan.jpg"];
        [picker dismissViewControllerAnimated:YES completion:^{}];
        [picker removeFromParentViewController];
        picker = nil;
        
        
        return ;
    }
}
//将图片上传至服务器
- (void)postFileWithPath:(NSString *)path param:(NSDictionary *)param image:(UIImage *)image
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:path parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        NSData *date = nil;
        NSString *mimeType = nil;
        NSString *strName = nil;
        if (UIImagePNGRepresentation(image) == nil) {
            date = UIImageJPEGRepresentation(image, 1);
            mimeType = @"image/jpeg";
            strName = @"shiyuan.jpg";
        }
        else {
            date = UIImagePNGRepresentation(image);
            mimeType = @"image/png";
            strName = @"shiyuan.png";
        }
            [formData appendPartWithFileData:date name:@"storePic" fileName:strName mimeType:mimeType];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [MBProgressHUD showSuccess:@"保存成功"];
        [[NSUserDefaults standardUserDefaults]setObject:@"haveChanged" forKey:@"changed"];
        [passValue passValue].accountHaveFlag = NO;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popToRootViewControllerAnimated:YES];
        });
//        [MBProgressHUD hideHUD];
           } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [MBProgressHUD showError:@"保存失败"];
    }];
}
//对图片尺寸进行压缩--
-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}
/**
 * 保存图片
 */
- (NSString *)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName{
    NSData* imageData;
    
    //判断图片是不是png格式的文件
    if (UIImagePNGRepresentation(tempImage))
    {
        //返回为png图像。
        imageData = UIImagePNGRepresentation(tempImage);
    }else {
        //返回为JPEG图像。
        imageData = UIImageJPEGRepresentation(tempImage, 1.0);
    }
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString* documentsDirectory = [paths objectAtIndex:0];
    NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
//    NSArray *nameAry=[fullPathToFile componentsSeparatedByString:@"/"];
//    NSLog(@"===fullPathToFile===%@",fullPathToFile);
//    NSLog(@"===FileName===%@",[nameAry objectAtIndex:[nameAry count]-1]);
    [imageData writeToFile:fullPathToFile atomically:NO];
    self.filePath = fullPathToFile;
    return fullPathToFile;
}

//时间转字符串
-(NSString *)toFormatTime:(NSDate *)time
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *strDate = [dateFormatter stringFromDate:time];
    return strDate;
}

//关闭劳动强度介绍
-(void)closeHelpView
{
    self.helpView.hidden = YES;
    self.xuanzeqiView.hidden = YES;
}
//打开劳动强度介绍
-(void)openHelpView
{
    self.helpView.hidden = NO;
    self.xuanzeqiView.hidden = NO;
}

//在帮助view上添加内容
-(void)addNeirongTohelpView:(UIView *)view
{
    CGFloat w = view.frame.size.width;
    CGFloat h = view.frame.size.height;
    
    CGFloat y = 20.0;
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, y, w, 30)];
    titleLabel.text = @"中国成人活动水平分级";
    titleLabel.textColor = YMColor(193, 58, 141);
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.helpView addSubview:titleLabel];
    y += titleLabel.frame.size.height + 10;
    
    UILabel *qingduLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
    qingduLabel.text = @"轻度体力活动：75%时间坐或站立、25%时间站着活动。例如：办公室工作、修理电器钟表、售货员、酒店服务员、化学实验操作、讲课等。";
    qingduLabel.textAlignment = NSTextAlignmentLeft;
    qingduLabel.font = [UIFont systemFontOfSize:15.0];
    NSDictionary * attribute2 = @{NSFontAttributeName:[UIFont systemFontOfSize:16.0]};
    CGSize size2 = [qingduLabel.text boundingRectWithSize:CGSizeMake(kDeviceWidth - 40, kDeviceHeight) options:NSStringDrawingUsesLineFragmentOrigin attributes:attribute2 context:nil].size;
    qingduLabel.lineBreakMode = NSLineBreakByWordWrapping;
    qingduLabel.numberOfLines = 0;
    qingduLabel.frame = CGRectMake(10, y, w - 20, size2.height);
    qingduLabel.textColor = YMColor(95, 95, 95);
    [self.helpView addSubview:qingduLabel];
    
    y += size2.height + 10;
    UILabel *zhongduduLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
    zhongduduLabel.text = @"中度体力活动：25%时间坐或站立、75%时间特殊活动。例如：学生日常活动、机动车驾驶、电工安装、车床操作、金工切割等。";
    zhongduduLabel.textAlignment = NSTextAlignmentLeft;
    zhongduduLabel.font = [UIFont systemFontOfSize:15.0];
    NSDictionary * attribute = @{NSFontAttributeName:[UIFont systemFontOfSize:16.0]};
    CGSize size = [zhongduduLabel.text boundingRectWithSize:CGSizeMake(kDeviceWidth - 40, kDeviceHeight) options:NSStringDrawingUsesLineFragmentOrigin attributes:attribute context:nil].size;
    zhongduduLabel.lineBreakMode = NSLineBreakByWordWrapping;
    zhongduduLabel.numberOfLines = 0;
    zhongduduLabel.frame = CGRectMake(10, y, w - 20, size.height);
    zhongduduLabel.textColor = YMColor(95, 95, 95);
    [self.helpView addSubview:zhongduduLabel];
    
    y += size.height + 10;
    UILabel *zhongduduLabel1 = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
    zhongduduLabel1.text = @"重度体力活动：40%时间坐或站立、60%时间特殊职业活动。例如：炼钢、舞蹈、体育运动、装卸、采矿等。";
    zhongduduLabel1.textAlignment = NSTextAlignmentLeft;
    zhongduduLabel1.font = [UIFont systemFontOfSize:15.0];
    NSDictionary * attribute3 = @{NSFontAttributeName:[UIFont systemFontOfSize:16.0]};
    CGSize size3 = [zhongduduLabel1.text boundingRectWithSize:CGSizeMake(kDeviceWidth - 40, kDeviceHeight) options:NSStringDrawingUsesLineFragmentOrigin attributes:attribute3 context:nil].size;
    zhongduduLabel1.lineBreakMode = NSLineBreakByWordWrapping;
    zhongduduLabel1.numberOfLines = 0;
    zhongduduLabel1.frame = CGRectMake(10, y, w - 20, size3.height);
    zhongduduLabel1.textColor = YMColor(95, 95, 95);
    [self.helpView addSubview:zhongduduLabel1];
    y += size3.height;
    
    UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    closeBtn.frame = CGRectMake(w / 3.0, y + (h - y - w / 3.0 / 2.22) / 2.0, w / 3.0, w / 3.0 / 2.22) ;
    closeBtn.backgroundColor = YMColor(252, 160, 207);
    [closeBtn setTitle:@"我知道了" forState:UIControlStateNormal];
    [closeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    closeBtn.layer.cornerRadius = 5.0;
    [self.helpView addSubview:closeBtn];
    [closeBtn addTarget:self action:@selector(closeHelpView) forControlEvents:UIControlEventTouchUpInside];
    
}
//计算两个日期间的天数
-(int)jisuantisnhu:(NSString *)currentStr  and:(NSString *)selectStr
{
    //首先创建格式化对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyyMMdd"];
    //然后创建日期对象
    NSDate *date1 = [dateFormatter dateFromString:currentStr];
    NSDate *date2 = [dateFormatter dateFromString:selectStr];
    NSDate *date = [NSDate date];
    //计算时间间隔（单位是秒）
    NSTimeInterval time1 = [date1 timeIntervalSinceDate:date];
    NSTimeInterval time2 = [date2 timeIntervalSinceDate:date];
    int time = (int)time1 - (int)time2;
    //计算天数、时、分、秒
    int days = ((int)time)/(3600*24);
    return days;
}

#pragma mark - UIPickerView
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    NSInteger number = 0;
    if(pickerView.tag == 1 || pickerView.tag == 3)
    {
        number = 1;
    }
    if(pickerView.tag == 4 || pickerView.tag == 5)
    {
        number = 2;
    }

    return number;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    NSInteger number = 0;
    if(pickerView.tag == 1)
    {
        number = self.heightIntArray.count;
    }
    if(pickerView.tag == 3)
    {
        number = self.workLevelArray.count;
    }
    if(pickerView.tag == 4 || pickerView.tag == 5)
    {
        if(component == 0)
        {
            number = self.weightIntArray.count;
        }
        else
        {
            number = self.weightFloattArray.count;
        }
    }
    
    return number;
    
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    NSString *dataStr = nil;
    if(pickerView.tag == 1)
    {
        dataStr = self.heightIntArray[row];
    }
    if(pickerView.tag == 3)
    {
        dataStr = self.workLevelArray[row];
    }
    if(pickerView.tag == 4 || pickerView.tag == 5)
    {
        if(component == 0)
        {
            dataStr = self.weightIntArray[row];
        }
        else
        {
            dataStr = self.weightFloattArray[row];
        }
    }
    return dataStr;
}


- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if(pickerView.tag == 1)
    {
        selectIntStr = self.heightIntArray[row];
    }
    if(pickerView.tag == 3)
    {
        selectIntStr = self.workLevelArray[row];
    }
    if(pickerView.tag == 4 || pickerView.tag == 5)
    {
        if(component == 0)
        {
            selectIntStr = self.weightIntArray[row];
        }
        else
        {
            selectFloatStr = self.weightFloattArray[row];
        }
    }
}

-(void)dealloc
{
    YMLog(@"完善界面消亡了");
}


@end
